import { ChangeDetectionStrategy, Component, EventEmitter, Inject, Input, OnChanges, Optional, Output, SimpleChanges } from "@angular/core";
import { FormArray, FormBuilder, FormGroup } from "@angular/forms";
import { MONK_FORMDEISGN_CONFIG, MonkFormDesignConfig } from "../../monk-form-design.interface";

@Component({
  // eslint-disable-next-line
  selector: 'app-design-form-batch',
  templateUrl: './design-form-batch.component.html',
  styleUrls: ['./design-form-batch.component.scss'],
  changeDetection: ChangeDetectionStrategy.Default
})
export class DesignFormBatchComponent implements OnChanges {
  @Input() formConfig: any;
  @Input() record: any;
  @Input() form: FormGroup;
  @Output() readonly previewOutput: EventEmitter<any> = new EventEmitter();

  public _columns: any[]

  get _formArrayControl(): FormArray {
    return this.form.get(this.record.key) as FormArray;
  }

  get scrollX() {
    return  this.record.list.filter(item => !item.options.hidden).length * 190 + 80
      + (!this.record.options.hideSequence ? 60 : 0) + 'px'
  }

  get isDisabled() {
    return this._formArrayControl?.disabled
  }

  getColumns() {
    const columns = [];
    if (!this.record.options.hideSequence) {
      columns.push({
        title: "序号",
        dataIndex: "sequence_index_number",
        width: "60px",
        align: "center",
        customRender: (text, record, index) => {
          return index + 1;
        }
      });
    }

    columns.push(
      ...this.record.list
        .filter(item => !item.options.hidden)
        .map((item, index) => {
          return {
            title: item.label,
            dataIndex: item.key,
            width: index === this.record.list.length - 1 ? "150px" : "210px",
            //scopedSlots: { customRender: item.key }
            item
          };
        })
    );

    columns.push({
      title: "操作",
      dataIndex: "dynamic-opr-button",
      fixed: "right",
      width: "80px",
      align: "center",
      scopedSlots: { customRender: "dynamic-opr-button" }
    });

    this._columns = columns;
  }

  constructor(
    @Optional() @Inject(MONK_FORMDEISGN_CONFIG) public config: MonkFormDesignConfig,
    private fb: FormBuilder
  ) {}

  ngOnChanges(changes: SimpleChanges): void {
    this.getColumns()
  }

  getAsAny(v: any) {
    return v as any
  }

  add() {
    const obj = this.record.list.reduce((prev, cur) => {
      prev[cur.key] = []
      return prev
    }, {})
    this._formArrayControl.push(
      this.fb.group(obj)
    );
  }

  removeDomain(index) {
    this._formArrayControl.removeAt(index)
  }
}